import { existsSync } from 'node:fs';
import { join } from 'node:path';

import { colors, consola, execaCommand, getPackages } from '@vben/node-utils';

import { cancel, isCancel, select } from '@clack/prompts';
import yaml from 'yamljs';

interface RunOptions {
  command?: string;
}
// , 'nw', 'tauri' 待完善
const platformTarget = ['web', 'electron'];
const platformTargetHint: Record<string, string> = {
  web: 'Build To Browser',
  electron: 'Build To Electron',
  nw: 'Build To Nwjs',
  tauri: 'Build To Tauri',
};
export async function run(options: RunOptions) {
  const { command } = options;
  if (!command) {
    console.error('Please enter the command to run');
    process.exit(1);
  }
  const { packages } = await getPackages();

  // const appPkgs = await findApps(process.cwd(), packages);
  // const websitePkg = packages.find(
  //   (item) => item.packageJson.name === '@vben/website',
  // );
  /**
   * add by lishibin 2025-05-14 增加平台选择
   */
  // 只显示有对应命令的包
  const selectPkgs = packages.filter((pkg: any) => {
    return (pkg?.packageJson as Record<string, any>)?.scripts?.[command];
  });
  const selectedPkg = (name: string) =>
    packages.find((pkg: any) => pkg?.packageJson.name === name);
  let selectPkg: string | symbol;
  let selectedTarget: string | symbol;
  if (selectPkgs.length > 1) {
    selectPkg = await select<string>({
      message: `Select the app you need to run [${command}]:`,
      options: selectPkgs.map((item: any) => ({
        label: item?.packageJson.name,
        value: item?.packageJson.name,
      })),
    });

    if (isCancel(selectPkg) || !selectPkg) {
      cancel('👋 Has cancelled');
      process.exit(0);
    }
  } else {
    selectPkg = selectPkgs[0]?.packageJson?.name ?? '';
  }

  if (!selectPkg) {
    console.error('No app found');
    process.exit(1);
  }
  const builderYmlPath = selectedPkg(selectPkg as string)
    ? join(selectedPkg(selectPkg as string).dir, 'builder.yml')
    : '';
  const yamlExists = selectedPkg(selectPkg as string)
    ? existsSync(builderYmlPath)
    : false;
  let envSetting = '';
  // add by lishibin 增加目标平台选择
  if (yamlExists) {
    const cfg = yaml.load(builderYmlPath);
    if (cfg.target && !platformTarget.includes(cfg.target)) {
      consola.error(
        `App Target Is Must In ${colors.greenBright(`${platformTarget}`)}\n`,
        `Please Check ${builderYmlPath} ${colors.cyan('target')}\n`,
        `✨Current ${colors.cyan('target')} Is ${colors.red(`${cfg.target}`)}`,
      );
      process.exit(1);
    }
    selectedTarget = await select<string>({
      message: `Select the app target to run [${command}]:`,
      options: platformTarget.map((item: string) => ({
        label: item,
        value: item,
        hint: platformTargetHint[item],
      })),
      initialValue: cfg.target,
    });

    if (isCancel(selectedTarget) || !selectedTarget) {
      cancel('👋 App Target Select Has cancelled');
      process.exit(0);
    }
    envSetting = `cross-env APP_TARGET=${selectedTarget as string} `;
  }
  execaCommand(
    `${envSetting}pnpm --filter=${selectPkg as string} run ${command}`,
    {
      stdio: 'inherit',
    },
  );
}

/**
 * 过滤app包
 * @param root
 * @param packages
 */
// async function findApps(root: string, packages: Package[]) {
//   // apps内的
//   const appPackages = packages.filter((pkg) => {
//     const viteConfigExists = fs.existsSync(join(pkg.dir, 'vite.config.mts'));
//     return pkg.dir.startsWith(join(root, 'apps')) && viteConfigExists;
//   });

//   return appPackages;
// }
